<template>
	<view class="page-cont" :style="themeStore.theme">
		<view class="nav-cont">
			<image class="nav-bg" src="/static/coldroom_background.png"></image>
			<image class="nav-back" :style="{top: statusBarHeight}" src="/static/back_arrow.png" @click="handleBack">
			</image>
			<view class="nav-box">
				<view class="nav-left">
					<view class="nav-room" @click="handleOpen">
						<view class="nav-room-name">{{facilityName}}</view>
						<image class="nav-room-arrow" src="/static/down_arrow.png"
							:style="{ transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)' }"></image>
					</view>
					<view class="nav-stat" v-if="projectType == 20">
						<view class="nav-stat-temp" v-if="statData.isTemp">
							<view class="nav-stat-temp-num">{{statData.temp}}</view>
							<view class="nav-stat-temp-unit">
								<view>°C</view>
								<view>温度</view>
							</view>
						</view>
						<image v-if="statData.isTemp" class="nav-stat-setting" src="/static/coldroom_temp.png"></image>
						<view v-if="statData.isHum" class="nav-stat-temp">
							<view class="nav-stat-temp-num">{{statData.hum}}</view>
							<view class="nav-stat-temp-unit">
								<view>%</view>
								<view>湿度</view>
							</view>
						</view>
					</view>
					<view class="nav-status" v-if="statData.isDif">
						<view class="nav-status-item">
							<view class="nav-status-item-name">化霜</view>
							<image class="nav-status-item-logo" src="/static/frost.png"></image>
						</view>
					</view>
				</view>
				<view class="nav-right">
					<image class="nav-right-logo" src="/static/fan_icon.png"></image>
				</view>
			</view>
		</view>
		<scroll-view class="main-cont" scroll-y enable-flex>
			<view class="tab-cont">
				<view class="tab-item">
					<image src="/static/fan_operation.png" class="tab-item-icon"></image>
					<text class="tab-item-name" @click="handleData">运行数据</text>
				</view>
				<view class="tab-item">
					<image src="/static/fan_alarm.png" class="tab-item-icon"></image>
					<text class="tab-item-name" @click="handleWarn">报警记录</text>
				</view>
				<view class="tab-item">
					<image src="/static/fan_maintain.png" class="tab-item-icon"></image>
					<text class="tab-item-name">维修记录</text>
				</view>
			</view>
			<view class="device-control">
				<view class="control-title">设备控制</view>
				<view class="control-list">
					<view v-for="(item, index) in controlList" :key="index"
						:class="['control-item', 'status' + item.status]" @click="handleControlClick(item)">
						<text :class="['iconfont', 'control-item-icon', item.icon]"></text>
						<view class="control-item-name">{{item.name}}</view>
					</view>
				</view>
			</view>
			<view class="device-setting">
				<view class="setting-item" v-for="(item, index) in settingList" :key="index">
					<view class="setting-item-top">
						<image class="setting-item-icon" src="/static/project-ice.png"></image>
						<view class="setting-item-info">
							<view class="setting-item-num">{{item.value}}</view>
							<view class="setting-item-unit">{{item.unit}}</view>
						</view>
					</view>
					<view class="setting-item-bottom">{{item.name}}</view>
				</view>
			</view>
		</scroll-view>
		<!-- 弹框选择标题 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff" @maskClick="isOpen = false" :visible="isOpen">
			<scroll-view class="popup-cont" scroll-y>
				<view class="popup-header">请选择</view>
				<view class="popup-title" v-for="(item, index) in facilityList" :key="index"
					@click="handleDeviceChange(item)">{{ item.name }}</view>
			</scroll-view>
		</uni-popup>
	</view>
</template>
<script setup lang="ts">
	import { reactive, ref, computed, onMounted, watch } from 'vue';
	import { onShow, onLoad } from '@dcloudio/uni-app';
	import { storeToRefs } from 'pinia';
	import { useNavbar } from '@/utils/hooks.js';
	import { getProjectModel, getProjectMonitor, getProjectAlarm, getRdcConf, getDevData, writeDevData } from "@/api/home.js";
	import useThemeStore from '@/store/theme';
	import useHomeStore from '@/store/home';
	import useUserStore from '@/store/user';
	const themeStore = useThemeStore();
	const homeStore = useHomeStore();
	const userStore = useUserStore();
	const { statusBarHeight, pageHeight } = useNavbar();
	const { projectType, deviceType, facilityName, facilityId, facilityList } = storeToRefs(homeStore);
	const popup = ref();
	const isOpen = ref(false);
	const statusObj = reactive({
		diff: 0,//化霜状态
		cold: 0,//制冷状态
		switch: 0,//运行状态
	});
	const keyList = ref([])
	// const controlActive = ref(0)
	const controlList = ref([])
	const ctlmapping = ref()
	const settingList = ref([])

	const statData = ref({
		temp: 0,//温度
		hum: 0,//湿度
		isTemp: false,//是否显示温度
		isHum: false,//是否显示湿度
		isDif: false,//是否显示化霜
	});


	// token= toke(反写数据不传参)
	const token = a => { let b = new Date()['getTime']() + '', c = a ? b['substr'](-0x3) + a['substr'](-0x1) : b['substr'](-0x4), d = (c * 0x21 - 0xb) * 0x16; return c + '' + d; };

	onMounted(() => {
		initData()
	});

	function initData() {
		if (deviceType.value == '26') {
			// 风机
			controlList.value = [
				{ name: "开关", icon: "icon-switch", status: 2, key: "switch" },
				{ name: "手动化霜", icon: "icon-dif", status: 2, key: "diff" },
				{ name: "远程控制", icon: "icon-control", key: "query" },
				{ name: "监控视频", icon: "icon-video", key: "video" }];
			keyList.value = [`26_0_${facilityId.value}_0`, `26_0_${facilityId.value}_1`];
		} else if (deviceType.value == '27') {
			// 灯组
			controlList.value = [{ name: "开关", icon: "icon-switch", status: 2, key: "switch" }];
			keyList.value = [`27_0_${facilityId.value}_0`];
		} else if (deviceType.value == '24') {
			// 门
			controlList.value = [{ name: "开关", icon: "icon-switch", status: 2, key: "switch" }];
			keyList.value = [`24_0_${facilityId.value}_0`];
		} else if (deviceType.value == '41') {
			// 压缩机
			controlList.value = [
				{ name: "开关", icon: "icon-switch", status: 2, key: "switch" },
				{ name: "远程控制", icon: "icon-control", key: "query" },
				{ name: "监控视频", icon: "icon-video", key: "video" }];
			keyList.value = [`41_0_${facilityId.value}_0`];
		} else if (deviceType.value == '31') {
			// 水泵
			controlList.value = [
				{ name: "开关", icon: "icon-switch", status: 2, key: "switch" },
				{ name: "远程控制", icon: "icon-control", key: "query" },
				{ name: "监控视频", icon: "icon-video", key: "video" }];
			keyList.value = [`31_0_${facilityId.value}_0`];
		} else if (deviceType.value == '32') {
			// 风扇
			controlList.value = [
				{ name: "开关", icon: "icon-switch", status: 2, key: "switch" },
				{ name: "远程控制", icon: "icon-control", key: "query" },
				{ name: "监控视频", icon: "icon-video", key: "video" }];
			keyList.value = [`32_0_${facilityId.value}_0`];
		}
		// getList();

		getRdcConfInfo();
	}

	const getRdcConfInfo = () => {
		ctlmapping.value = {}
		settingList.value = []
		getRdcConf({ mid: homeStore.projectId, type: homeStore.deviceType, id: homeStore.facilityId, loadctl: true }).then(res => {
			if (res.data && res.data.length && res.data[0].ctlmapping) {

				ctlmapping.value = JSON.parse(res.data[0].ctlmapping);
				settingList.value = ctlmapping.value.other.points
				console.log("ctlmapping", ctlmapping)
				if (ctlmapping.value.base['disable']) {
					let disable = ctlmapping.value.base['disable'];
					//开关
					getDevDataInfo("switch", disable.devtype, disable.apid, disable.devid, disable.points.name, disable.points.id)
				}
				if (ctlmapping.value.base['humidify']) {
					//化霜
					let humidify = ctlmapping.value.base['humidify'];
					getDevDataInfo("diff", humidify.devtype, humidify.apid, humidify.devid, humidify.points.name, humidify.points.id)
				}
				if (settingList.value.length) {
					getDevOtherDataInfo()
				}
			}
		})
	}

	const getDevDataInfo = (key, type, apid, devid, name, id) => {
		let params = {
			mid: homeStore.projectId,
			type: type,
			apid: apid,
			devid: devid,
			names: name,
			ids: id
		};
		getDevData(params).then(res => {
			if (res.data && res.data.length) {
				controlList.value.forEach(element => {
					if (element.key == key) {
						element.status = res.data[0].value;
					}
				});
			}
		})
	}

	const getDevOtherDataInfo = () => {
		let grpName = settingList.value.map(element => {
			return element.grpName;
		})
		let name = settingList.value.map(element => {
			return element.name;
		})
		let id = settingList.value.map(element => {
			return element.id;
		})
		let params = {
			mid: homeStore.projectId,
			type: ctlmapping.value.other.devtype,
			apid: ctlmapping.value.other.apid,
			devid: ctlmapping.value.other.devid,
			names: name,
			groups: grpName,
			ids: id
		};
		getDevData(params).then(res => {
			if (res.data && res.data.length) {
				res.data.forEach(item => {
					settingList.value.forEach(childItem => {
						if (item.id == childItem.id) {
							if (childItem.dataType == 0) {
								// 0：关，1：开
								childItem.value = item.value == 0 ? "关" : "开";
							} else {
								childItem.value = item.value;
							}
						}
					})
				})
			}
		})
	}

	// 获取设备数据
	function getList() {
		getProjectMonitor({ keys: keyList.value }).then(res => {
			if (deviceType.value == "26") {
				// 风机：制冷、化霜、开关
				statusObj.diff = Number(res[`26_0_${facilityId.value}_0`] || 0);//制冷状态，0：关，1：开
				statusObj.cold = Number(res[`26_0_${facilityId.value}_1`] || 0);//化霜状态，0：关，1：开
				controlList.value.forEach(element => {
					if (element.key == "diff") {
						element.status = statusObj.diff;
					}
				});
			} else {
				// 灯、门、压缩机、水泵、风扇：只有开关
				statusObj.switch = Number(res[keyList.value[0]] || 0);//制冷状态，0：关，1：开
				controlList.value.forEach(element => {
					if (element.key == "switch") {
						element.status = statusObj.switch;
					}
				});
			}
		});
	}



	// 下拉选择风机
	function handleOpen() {
		isOpen.value = true;
		popup.value.open();
	}

	// 风机选中
	function handleDeviceChange(e) {
		popup.value.close();
		homeStore.setFacilityId(e.id);
		homeStore.setFacilityName(e.name);
		initData()

	}

	// 设备控制
	function handleControlClick(e) {
		if (userStore.auth['/devmanage'] && userStore.auth['/devmanage']['data_writ']) {
			//用户权限校验

			if (e.status == 2) {
				uni.showToast({
					title: '未配置' + e.name + '相关点位',
					icon: 'none'
				});
				return;
			}

			let statusText = e.status == 1 ? '关闭' : '开启';
			switch (e.key) {
				case 'query':
					// 远程控制
					break
				case 'video':
					// 监控视频
					break
				case "switch":
					//开关
					uni.showModal({
						title: '温馨提示',
						content: '确认' + statusText + '?',
						showCancel: true,
						cancelText: '取消',
						confirmText: '确认',
						success: res => {
							if (res.confirm) {
								writeDevDataInfo(e)
							}
						},
					});
					break
				case "diff":
					statusText = e.status == 1 ? '关闭化霜' : '开启化霜';
					//化霜
					uni.showModal({
						title: '温馨提示',
						content: '确认' + statusText + '?',
						showCancel: true,
						cancelText: '取消',
						confirmText: '确认',
						success: res => {
							if (res.confirm) {
								writeDevDataInfo(e)
							}
						},
					});
					break

			}

		} else {
			uni.showToast({
				title: '当前用户无配置权限',
				icon: 'none'
			});

		}
	}

	const writeDevDataInfo = (e) => {
		if (ctlmapping.value && ctlmapping.value.base) {

			// console.log("token",token(null))
			let params = {
				token: token(null),
				mid: homeStore.projectId,
				type: undefined,
				apid: undefined,
				devid: undefined,
				name: undefined,
				group: undefined,
				itemid: undefined,
				value: e.status == 0 ? 1 : 0,
				oldvalue: e.status,
			};
			switch (e.key) {
				case "switch":
					if (ctlmapping.value.base['disable']) {
						let disable = ctlmapping.value.base['disable'];
						params.type = disable.devtype;
						params.apid = disable.apid;
						params.devid = disable.devid;
						params.name = disable.points.name;
						params.group = disable.points.grpName;
						params.itemid = disable.points.id;
						//开关
						// getDevDataInfo("switch", disable.devtype, disable.apid, disable.devid, disable.points.name, disable.points.id)
					}
					break
				case "diff":
					if (ctlmapping.value.base['humidify']) {
						//化霜
						let humidify = ctlmapping.value.base['humidify'];
						params.type = humidify.devtype;
						params.apid = humidify.apid;
						params.devid = humidify.devid;
						params.name = humidify.points.name;
						params.group = humidify.points.grpName;
						params.itemid = humidify.points.id;
						// getDevDataInfo("diff", humidify.devtype, humidify.apid, humidify.devid, humidify.points.name, humidify.points.id)
					}
					break
			}
			writeDevData(params).then(res => {
				//todo  成功后操作
			})
		} else {
			uni.showToast({
				title: '缺少ctlmapping信息',
				icon: 'none'
			});
		}
	}

	// 运行数据
	function handleData() {
		uni.navigateTo({
			url: '/pages/home/fan-detail',
		});
	}

	// 报警记录
	function handleWarn() { }

	// 返回
	function handleBack() {
		uni.navigateBack({
			delta: 1
		});
	}
</script>
<style lang="scss" scoped>
	.page-cont {
		position: relative;
		height: 100vh;

		.nav-cont {
			position: relative;
			padding-top: 95px;
			padding-bottom: 15px;

			.nav-bg {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 200px;
				z-index: 1;
			}

			.nav-back {
				position: absolute;
				top: 50px;
				left: 10px;
				padding: 10px;
				width: 40px;
				height: 40px;
				box-sizing: border-box;
				z-index: 2;
			}

			.nav-box {
				position: relative;
				display: flex;
				align-items: center;
				z-index: 3;
			}

			.nav-left {
				padding: 0 20px;
				width: 50%;
			}

			.nav-right {
				width: 50%;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.nav-right-logo {
				width: 100px;
				height: 60px;
			}

			.nav-room {
				display: flex;
				align-items: center;
			}

			.nav-room-name {
				color: #fff;
				font-size: 18px;
				font-weight: 600;
			}

			.nav-room-arrow {
				width: 12px;
				height: 12px;
			}

			.nav-stat {
				margin-top: 10px;
				display: flex;
				align-items: center;
			}

			.nav-stat-temp {
				display: flex;
				align-items: center;
			}

			.nav-stat-setting {
				margin-left: 10px;
				margin-right: 30px;
				width: 15px;
				height: 15px;
			}

			.nav-stat-temp-num {
				color: #fff;
				font-size: 25px;
				font-weight: 600;
			}

			.nav-stat-temp-unit {
				padding-left: 5px;
				color: #fff;
				font-size: 9px;
			}

			.nav-status {
				margin-top: 15px;
				display: flex;
			}

			.nav-status-item {
				padding: 0 10px;
				height: 18px;
				display: flex;
				align-items: center;
				border-radius: 9px;
				border: 1px solid #FFFFFF;
				background: linear-gradient(180deg, rgba(236, 239, 247, 1), rgba(255, 255, 255, 1));
				box-shadow: 0px 0px 10px 0px rgba(95, 131, 249, 0.2);
			}

			.nav-status-item-name {
				color: #5F83F9;
				font-size: 13px;
			}

			.nav-status-item-logo {
				padding-left: 5px;
				width: 12px;
				height: 12px;
			}
		}

		.main-cont {
			position: relative;
			padding: 10px;
			height: calc(100% - 170px);
			box-sizing: border-box;
			z-index: 4;
		}

		.tab-cont {
			display: flex;

			.tab-item {
				margin-left: 10px;
				padding: 0 10px;
				height: 40px;
				flex: 1;
				display: flex;
				align-items: center;
				border: 1px solid #fff;
				border-radius: 5px;
				background: linear-gradient(180deg, rgba(255, 255, 255, 1), rgba(238, 240, 249, 1));
				box-shadow: 0px 10px 20px 0px rgba(95, 131, 249, 0.1);

				&:first-child {
					margin-left: 0;
				}
			}

			.tab-item-icon {
				width: 12px;
				height: 12px;
			}

			.tab-item-name {
				margin-left: 8px;
				color: #333;
				font-size: 13px;
			}
		}

		.device-control {
			margin-top: 15px;
			padding: 10px;
			border-radius: 5px;
			background-color: #fff;
			box-shadow: 0px 10px 10px 0px rgba(135, 166, 233, 0.1);
			box-sizing: border-box;

			.control-title {
				color: #333;
				font-size: 14px;
				font-weight: 600;
			}

			.control-list {
				margin-top: 20px;
				padding: 0 10px;
				display: flex;
				box-sizing: border-box;
			}

			.control-item {
				margin-left: 15px;
				padding: 10px;
				flex: 1;
				text-align: center;
				border-radius: 5px;
				background-color: #F2F4FB;
				box-sizing: border-box;

				&:first-child {
					margin-left: 0;
				}
			}

			.control-item-icon {
				color: #5A6570;
				font-size: 14px;
			}

			.control-item-name {
				margin-top: 10px;
				color: #5A6570;
				font-size: 11px;
			}

			.status0 {
				background-color: #FF916C;

				.control-item-icon,
				.control-item-name {
					color: #fff;
				}
			}

			.status1 {
				background-color: $theme-color;

				.control-item-icon,
				.control-item-name {
					color: #fff;
				}
			}

			.status2 {
				background-color: #F2F4FB;

				.control-item-icon,
				.control-item-name {
					color: #5A6570;
				}
			}
		}

		.device-setting {
			margin-top: 20px;
			display: flex;
			flex-wrap: wrap;

			.setting-item {
				margin-left: 12px;
				padding: 10px;
				width: calc(33.33% - 8px);
				border-radius: 5px;
				border: 1px solid #fff;
				background-color: #F2F4FB;
				box-sizing: border-box;

				&:nth-child(3n + 1) {
					margin-left: 0;
				}

				&:nth-child(n + 4) {
					margin-top: 15px;
				}
			}

			.setting-item-top {
				display: flex;
				align-items: center;
			}

			.setting-item-icon {
				width: 35px;
				height: 35px;
			}

			.setting-item-info {
				margin-left: 5px;
			}

			.setting-item-num {
				color: #5A6570;
				font-size: 17px;
				font-weight: 600;
			}

			.setting-item-unit {
				color: #999;
				font-size: 13px;
				font-weight: 600;
			}

			.setting-item-bottom {
				margin-top: 9px;
				color: #5A6570;
				font-size: 11px;
			}
		}
	}

	.popup-cont {
		max-height: 60vh;
		background: #fff;
		overflow: hidden;
		overflow-y: auto;
		z-index: 100;

		.popup-title,
		.popup-header {
			height: 100rpx;
			line-height: 100rpx;
			color: #333;
			font-size: 28rpx;
			text-align: center;
			border-top: 2rpx solid #eee;
		}

		.popup-header {
			font-size: 32rpx;
			font-weight: 600;
		}
	}
</style>